﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using Caliburn.Micro;
using JY.Wpf.Core.Tools;
using SD.IOC.Core.Mediators;

namespace JY.Wpf.Core.CaseForCaliburn
{
    /// <summary>
    /// 引导程序
    /// </summary>
    public class JYBootstrapperBase : BootstrapperBase
    {
        #region # 构造器
        /// <summary>
        /// 构造器
        /// </summary>
        public JYBootstrapperBase()
        {
            ViewLocator.NameTransformer.AddRule
            (
                @"(?<nsfull>((?<nsroot>[A-Za-z_]\w*\.)(?<nsstem>([A-Za-z_]\w*\.)*))?(?<nsleaf>[A-Za-z_]\w*\.))?(?<basename>[A-Za-z_]\w*)(?<suffix>ViewModel$)",
                @"nsfull=${nsfull}, nsroot=${nsroot}, nsstem=${nsstem}, nsleaf=${nsleaf}, basename=${basename}, suffix=${suffix}"
            );
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            this.Initialize();
        }
        #endregion

        #region # 程序退出——void OnExit(object sender, EventArgs e)
        /// <summary>
        /// 程序退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected override void OnExit(object sender, EventArgs e)
        {
            Application.Current.Shutdown();
            Process.GetCurrentProcess().Close();
            Process.GetCurrentProcess().CloseMainWindow();
            Process.GetCurrentProcess().Kill();
            Environment.Exit(0);
        }
        #endregion

        #region # 应用程序启动事件——void OnStartup(object sender, StartupEventArgs e)
        /// <summary>
        /// 应用程序启动事件
        /// </summary>
        protected override void OnStartup(object sender, StartupEventArgs e)
        {

        }
        #endregion

        #region # 配置——void Configure()
        /// <summary>
        /// 配置
        /// </summary>
        protected override void Configure()
        {
            #region 按键注册
            var defaultCreateTrigger = Parser.CreateTrigger;

            Parser.CreateTrigger = (target, triggerText) =>
            {
                if (triggerText == null)
                {
                    return defaultCreateTrigger(target, null);
                }

                var triggerDetail = triggerText
                    .Replace("[", string.Empty)
                    .Replace("]", string.Empty);

                var splits = triggerDetail.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);

                switch (splits[0])
                {
                    case "Key":
                        var key = (Key)Enum.Parse(typeof(Key), splits[1], true);
                        return new KeyTrigger { Key = key };

                    case "Gesture":
                        var mkg = (MultiKeyGesture)(new MultiKeyGestureConverter()).ConvertFrom(splits[1]);
                        return new KeyTrigger { Modifiers = mkg.KeySequences[0].Modifiers, Key = mkg.KeySequences[0].Keys[0] };
                }

                return defaultCreateTrigger(target, triggerText);
            };
            #endregion
        }
        #endregion

        #region # 异常处理

        #region # 当前线程异常捕获事件——void OnUnhandledException
        /// <summary>
        /// 异常事件
        /// </summary>
        protected override void OnUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            e.Handled = true;
            ResolveMediator.Resolve<IExceptionHelper>().ExceptionHandling(e.Exception,this.AutoLogin);
        }

        #endregion

        #region # 非UI线程异常事件——void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)

        /// <summary>
        /// 非UI线程异常事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;
            if (ex == null) return;

            ResolveMediator.Resolve<IExceptionHelper>().ExceptionHandling(ex, this.AutoLogin);
        }
        #endregion

        #region # 自动登录——virtual void AutoLogin()
        /// <summary>
        /// 自动登录
        /// </summary>
        /// <returns></returns>
        public virtual void AutoLogin()
        {
        }
        #endregion
        #endregion

        #region # 解析服务实例—— object GetInstance(Type service, string key)
        /// <summary>
        /// 解析服务实例
        /// </summary>
        protected override object GetInstance(Type service, string key)
        {
            if (service == null) return null;
            object instance = ResolveMediator.Resolve(service);
            return instance;
        }
        #endregion

        #region # 解析服务实例列表——IEnumerable<object> GetAllInstances(Type service)
        /// <summary>
        /// 解析服务实例列表
        /// </summary>
        protected override IEnumerable<object> GetAllInstances(Type service)
        {
            IEnumerable<object> instances = ResolveMediator.ResolveAll(service);
            return instances;
        }
        #endregion
    }
}
